package com.framework.foundation.weixin.wxstore;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import com.framework.foundation.common.BaseService;
import com.framework.foundation.common.vo.BTResult;
import com.framework.foundation.common.vo.IResult;
import com.framework.foundation.common.vo.Result;
import com.framework.foundation.util.ApiConfigUtils;
import com.framework.foundation.util.Collections3;
import com.framework.foundation.weixin.api.WifiApi;
import com.framework.foundation.weixin.wxuser.Wxuser;
import com.jfinal.aop.Before;
import com.jfinal.aop.Enhancer;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.api.ApiResult;

public class WxstoreService extends BaseService<Wxstore> {

	public static final Log LOG = Log.getLog(WxstoreService.class);

	public static final WxstoreService me = Enhancer.enhance(WxstoreService.class);

	/**
	 * 新增方法
	 * 
	 * @return
	 * @Author: Brin
	 * @Date: 2015年11月10日 下午1:58:08
	 */
	@Override
	@Before(Tx.class)
	public IResult<Object> save(Wxstore model) {
		try {
			if (null == model) {
				return Result.createFail(model);
			}
			// 暂时默认宜昌市政府经纬度
			Boolean result = model.save();

			if (result) {
				ApiConfigUtils.setApiConfig(model.getInt("wxuser_id"));
				// 通过微信接口创建门店
				ApiResult apiResult = WifiApi.addStore(model);
				if (apiResult.isSucceed()) {
					// 查询wifi门店信息并绑定shop_id到本地门店
					Map wifiStore = findShopId(model.getInt("id"), 1);
					if (wifiStore == null) {
						LOG.error("wifi门店中无法找到对应的shop_id信息！");
						// 微信删除门店
						return Result.createFail();
					} else {
						// 保存关键的shop_id到本地门店
						model.set("shop_id", wifiStore.get("shop_id"));
						return Result.create(model.update());
					}
				} else {
					// 删除本地门店
					model.delete();
					return Result.createFail(apiResult.getStr("errmsg"));
				}

			} else {
				return Result.createFail();
			}

		} catch (Exception e) {
			throw new RuntimeException("新增异常！", e);
		}
	}

	/**
	 * 编辑方法
	 * 
	 * @return
	 * @Author: Brin
	 * @Date: 2015年11月10日 下午1:58:08
	 */
	@Override
	public IResult<Object> update(Wxstore model) {
		try {
			if (null == model) {
				return Result.createFail(model);
			}
			return Result.create(model.update(), model);
		} catch (Exception e) {
			throw new RuntimeException("编辑异常！", e);
		}
	}

	@Override
	public BTResult<Record> paginate(Map<String, Object> param) {
		String select = "SELECT s.*, u.name AS wxuser_name, (SELECT count(m.id) FROM ww_mac m WHERE m.store_id = s.id) AS mac_count, (SELECT count(d.id) FROM ww_device d WHERE d.store_id = s.id) AS device_count";
		StringBuffer from = new StringBuffer("FROM ww_store s");
		from.append(" LEFT JOIN ww_wxuser u ON s.wxuser_id = u.id");
		from.append(" WHERE s.deleteMark = 0");
		if (param.get("business_name") != null) {
			from.append(" AND s.business_name like '%" + param.get("business_name").toString() + "%'");
		}
		if ((param.get("wxuser_id") != null) && StringUtils.isNotBlank(param.get("wxuser_id").toString())) {
			from.append(" AND s.wxuser_id = " + Integer.parseInt(param.get("wxuser_id").toString()));
		}
		from.append(" ORDER BY s.id ASC ");

		Page<Record> pages = Db.paginate(MapUtils.getInteger(param, "pageNumber"),
				MapUtils.getInteger(param, "pageSize"), select, from.toString(), new Object[0]);
		return new BTResult<Record>(pages.getTotalRow(), pages.getList());
	}

	public IResult<Object> homepage(Map<String, Object> param) {
		String[] ids = MapUtils.getString(param, "ids").split(",");
		for (String id : ids) {
			Wxstore store = Wxstore.me.findById(id);
			// 设置商家主页
			ApiConfigUtils.setApiConfig(store.getInt("wxuser_id"));
			store.set("homepage", param.get("homepage"));
			ApiResult result1 = WifiApi.updateStoreHomePage(store);
			String errmsg = "";
			if (result1.isSucceed()) {
				// 只修改商家主页
				store.update();
			} else {
				store.remove("homepage");
				errmsg = result1.getStr("errmsg");
			}
			// 设置顶部常驻入口文案
			store.set("bar_type", Integer.parseInt(param.get("bar_type").toString()));
			ApiResult result2 = WifiApi.updateStoreBar(store);
			if (result2.isSucceed()) {
				store.update();
			} else {
				errmsg += "\n" + result2.getStr("errmsg");
			}

			if (StringUtils.isNotBlank(errmsg)) {
				return Result.createFail(errmsg);
			}

		}
		return Result.createSuccess();
	}

	/**
	 * 
	 * @param ids
	 * @return
	 * @Author: Brin
	 * @Date: 2016年3月22日 上午10:41:26
	 */
	public IResult<Object> clearDevice(String[] ids) {
		try {
			if (ArrayUtils.isEmpty(ids)) {
				return Result.createFail(0);
			}
			// 微信删除
			for (String id : ids) {
				Wxstore store = Wxstore.me.findById(Integer.parseInt(id));
				ApiConfigUtils.setApiConfig(store.getInt("wxuser_id"));
				ApiResult result = WifiApi.deleteAllDevice(store);
				if (result.isSucceed()) {
					// 删除设备
					Db.update("DELETE FROM ww_mac WHERE store_id = ?", store.getInt("id"));
					// 删除网络
					Db.update("DELETE FROM ww_device WHERE store_id = ?", store.getInt("id"));
				} else {
					return Result.createFail(result.getStr("errmsg"));
				}
			}
			return Result.createSuccess();

		} catch (Exception e) {
			throw new RuntimeException("删除异常---->" + getClass().getSuperclass().getSimpleName(), e);
		}
	}

	/**
	 * 查询wifi门店列表并搜索出sid对应的门店shop_id
	 * 
	 * @Author: Brin
	 * @Date: 2016年3月15日 下午2:19:19
	 */
	public Map findShopId(int sid, int pageindex) {
		ApiResult result = WifiApi.getWifiStoreList(pageindex);
		if (result.isSucceed()) {
			Map data = result.getMap("data");
			int pagecount = (Integer) data.get("pagecount");
			List records = (List) data.get("records");
			if ((Integer) data.get("totalcount") > 0) {
				for (int i = 0; i < records.size(); i++) {
					Map record = (Map) records.get(i);
					String recordSid = record.get("sid").toString();
					if (recordSid.equals(String.valueOf(sid))) {
						return record;
					} else {
						// 递归寻找
						if (pageindex != pagecount) {
							return findShopId(sid, pageindex++);
						}
					}
				}
			}

		}
		return null;
	}

	/**
	 * 同步微信平台数据
	 * 
	 * @param param
	 * @return
	 * @Author: Brin
	 * @Date: 2016年3月18日 下午3:20:16
	 */
	@Before(Tx.class)
	public boolean synchrony() {
		// 获取所有公众号信息
		List<Wxuser> list = Wxuser.me.find("SELECT * FROM ww_wxuser");
		if (CollectionUtils.isNotEmpty(list)) {
			List<Wxstore> addStoreList = new ArrayList<Wxstore>();
			for (Wxuser wxuser : list) {
				ApiConfigUtils.setApiConfig(wxuser.getInt("id"));
				List<Map<String, Object>> wifiStoreList = WifiApi.getAllWifiStoreList();
				List<Wxstore> localStoreList = Wxstore.me.find("SELECT * FROM ww_store WHERE wxuser_id = ?",
						wxuser.getInt("id"));
				List shopIdList = Collections3.extractToList(wifiStoreList, "shop_id");
				List localShopIdList = Collections3.extractToList(localStoreList, "shop_id", "get");
				shopIdList.removeAll(localShopIdList);
				if (CollectionUtils.isNotEmpty(shopIdList)) {
					for (Map<String, Object> wifiStore : wifiStoreList) {
						int shopId = (Integer) wifiStore.get("shop_id");
						if (shopIdList.contains(shopId)) {
							String wifiSid = wifiStore.get("sid").toString();
							String shopName = wifiStore.get("shop_name").toString();
							// 重新添加缺少的门店信息
							Wxstore wxstore = new Wxstore();
							wxstore.set("shop_id", shopId);
							wxstore.set("business_name", shopName);
							wxstore.set("wxuser_id", wxuser.getInt("id"));
							// 根据sid或者名称逐一比对获得门店具体信息
							// sid比对主要针对通过本系统后台添加的门店信息遗漏的情况
							// 名称比对主要针对非本系统后台添加的门店信息遗漏情况
							List<Map<String, Object>> storeList = WifiApi.getAllStoreList();
							for (Map<String, Object> store : storeList) {
								Map<String, Object> baseInfo = (Map<String, Object>) store.get("base_info");
								String sid = baseInfo.get("sid").toString();
								String businessName = baseInfo.get("business_name").toString();
								String branchName = baseInfo.get("branch_name").toString();
								if (StringUtils.isNotBlank(branchName)) {
									businessName += "(" + branchName + ")";
								}
								if ((StringUtils.isNotBlank(wifiSid) && wifiSid.equals(sid))
										|| shopName.equals(businessName)) {
									wxstore.set("province", baseInfo.get("province"));
									wxstore.set("city", baseInfo.get("city"));
									wxstore.set("district", baseInfo.get("district"));
									wxstore.set("longitude", baseInfo.get("longitude"));
									wxstore.set("latitude", baseInfo.get("latitude"));
									wxstore.set("telephone", baseInfo.get("telephone"));
									wxstore.set("address", baseInfo.get("address"));
									wxstore.set("categories", StringUtils.join((List) baseInfo.get("categories"), ","));
								}
							}
							// 获取门店wifi信息
							ApiResult wifiResult = WifiApi.getWifiInfo(shopId);
							if (wifiResult.isSucceed()) {
								Map<String, Object> data = wifiResult.getMap("data");
								wxstore.set("homepage", data.get("homepage_url"));
								wxstore.set("bar_type", data.get("bar_type"));
							}
							addStoreList.add(wxstore);
						}
					}
				}
			}
			// 清空门店信息
			// Db.update("DELETE FROM ww_store");
			// 批量添加门店
			Db.batchSave(addStoreList, addStoreList.size());
			return true;
		}

		return false;
	}
}
